new Vue({
    el: '#app',
    data() {
        return {
            //修改大模型悬浮框是否可以点击
            changeMultiBtn: true,
            showPopover: true,
            //流式控制器
            abortCtrl: null,
            streaming: false,
            isflageIOX: true,

            //i国网录音相关
            voicelist: [],
            timetimer1:null,
            isFlagStartTrue: false,

            clipboard: {
                content: "",
            },
            writingType: 5,
            //步骤
            stepList: [{ id: '1', acIcon: '../images/write/voice-turn-ac.png', disIcon: '../images/write/voice-turn-ac.png', step: 1 },
                { id: '2', acIcon: '../images/write/step2-ac.png', disIcon: '../images/write/step2-dis.png', step: 2 },
                { id: '3', acIcon: '../images/write/step3-ac.png', disIcon: '../images/write/step3-dis.png', step: 4 },
                { id: '4', acIcon: '../images/write/assist-step4-ac.png', disIcon: '../images/write/assist-step4-dis.png', step: 5 },
            ],
            //接口调用sessionId
            infSessionId: '',
            activeTitle: 1,
            outlineValue: '一级大纲',
            outlineShow: false,
            outlineOptions: [
                { text: '一级大纲', value: 1 },
                { text: '二级大纲', value: 2 },
                { text: '三级大纲', value: 3 }
            ],
            //当前步骤:1-生成大纲页面2-大纲编辑页面3-生成内容页面4-文档校核页面5-生成方案页面
            currentStep: 2,
            form: {
                subjectTitle: '',
                contentNeed: '',
                notificationFile: {
                    // "id": "1",
                    // "fileName": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.pdf",
                    // "type": "PDF",
                    // "img": "pdf",
                    // "fileSize": 878
                },
                recordFile: {
                    // "id": "1",
                    // "fileName": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.doc",
                    // "type": "WORD",
                    // "img": "word",
                    // "fileSize": 878
                },
                highlight:''
            },
            //模板列表
            modelList: [
                { id: '-1', modelName: '', img: '../../../image/loading2.gif' },
                // { id: '1', modelName: '', logo: '../images/write/model1.png' },
                // { id: '2', modelName: '', logo: '../images/write/model2.png' },
                // { id: '3', modelName: '', logo: '../images/write/model1.png' },
                // { id: '4', modelName: '', logo: '../images/write/model2.png' },
                // { id: '5', modelName: '', logo: '../images/write/model1.png' },
                // { id: '6', modelName: '', logo: '../images/write/model2.png' }
            ],
            //素材列表
            materialList: [
                // { id: '1', fileName: '关于XXX的工作方案.docx', type: 'word', fileSize: '120.3KB' },
                // { id: '2', fileName: '关于XXXXX的工作方案.docx', type: 'word', fileSize: '136.52KB' },
                // { id: '3', fileName: '关于XXX的工作方案.docx', type: 'word', fileSize: '120.3KB' },
                // { id: '4', fileName: '关于XXXXX的工作方案.docx', type: 'word', fileSize: '136.52KB' },
            ],
            //当前选中模板
            curModelId: '',
            //图片预览
            modelImageShow: false,
            modelImages: [],
            modelImageIndex: 0,
            curPId: '',
            //大纲内容
            outLineMdContent: '',
// `# 标题一
// 内容一人工智能是xxxxxxxxx内容一人工智能是xxxxxxxxx
// ## 标题二
// 这个妹妹很骚包
// ### 标题三
// 这篇文章写的很犀利
// 1.列表一
// 2.列表二
// 3.列表三
// #### 标题四
// - First item
// - Second item
// - Third item`,
            outLineContent: '',
            //修改中的大纲内容
            editPContent: '',
            //word格式方案
            wordResult: {
                // id: '1', fileName: '人工智能：塑造未来的技术力量.docx', type: 'word', fileSize: '126.35KB' 
            },
            //ppt格式方案
            pptResult: {
                // id: 'a'
            },
            //ppt结果显示
            pptLoading: false,
            //显示编辑大纲弹窗
            canEditContent: false,
            focus: false,
            requireText: '',
            chatting: false,
            //选中续写等功能
            quickSel: '',
            quickList: [{ id: '1', title: '扩写', type: 'expand' }, { id: '2', title: '续写', type: 'continued' },{ id: '4', title: '缩写', type: 'abbreviation' }, { id: '3', title: '润色', type: 'polish' }],
            //扩写、续写、润色生成的待替换内容
            replaceContent: '',
            //扩写、续写、润色生成md转html
            replaceHtmlContent:'',
            //方案内容
            programMdContent: '',
// `\`\`\`markdown
// ## 一、工作回顾

// 在过去的一段时间里，我致力于高效完成各项工作任务，确保每一项工作都能达到既定的标准和要求。通过不断学习和实践，我在专业技能和综合素质上均取得了显著提升。

// ### （一）项目执行情况

// 1. **项目A**：作为核心成员，我全程参与了项目A的规划、实施与收尾工作。在项目执行过程中，我积极沟通协调，确保项目按计划顺利推进。通过团队的努力，项目A最终成功交付，并获得了客户的高度评价。

// 2. **项目B**：针对项目B的复杂性和紧迫性，我主动承担起了关键任务。通过深入分析项目需求，我制定了详细的工作计划，并带领团队高效执行。在项目遇到挑战时，我能够迅速调整策略，确保项目按时按质完成。

// ### （二）技能提升与学习

// 1. **专业技能**：为了更好地适应工作需求，我不断学习和掌握新技能。通过参加专业培训、阅读专业书籍和在线课程，我在XX领域取得了显著进步，为工作的顺利开展提供了有力支持。

// 2. **综合素质**：在工作中，我注重培养自己的综合素质。通过参与团队建设、沟通协调和解决问题等实践活动，我的团队协作能力、沟通能力和应变能力均得到了显著提升。

// ## 二、工作反思

// 在回顾过去的工作时，我也深刻认识到自己存在的不足和需要改进的地方。

// ### （一）存在的问题

// 1. **时间管理**：在部分项目中，由于时间管理不当，导致部分工作进度滞后。这在一定程度上影响了项目的整体进度和效率。

// 2. **沟通效率**：在团队沟通中，有时存在信息传递不畅或理解偏差的情况。这在一定程度上影响了团队的协作效率和工作质量。

// ### （二）改进措施

// 1. **优化时间管理**：制定更加合理的时间计划表，明确各项工作的优先级和完成时间。同时，加强自我监督和管理，确保工作按计划有序进行。

// 2. **提升沟通效率**：加强团队之间的沟通协作，确保信息传递的准确性和及时性。同时，注重沟通技巧和方法的学习和运用，提高沟通效率和质量。

// ## 三、未来展望

// 展望未来，我将继续秉承敬业、专业、创新的精神，不断提升自己的综合素质和专业技能。同时，我也将积极适应公司的发展需求和市场变化，为公司的发展贡献自己的力量。

// ### （一）个人发展规划

// 1. **深化专业技能**：继续深入学习和掌握XX领域的专业知识和技能，提高自己的专业素养和竞争力。

// 2. **拓宽知识领域**：关注行业动态和前沿技术发展趋势，积极拓宽自己的知识领域和视野。

// ### （二）团队贡献

// 1. **加强团队协作**：积极参与团队建设活动，加强与团队成员之间的沟通和协作，提高团队的凝聚力和战斗力。

// 2. **分享经验成果**：将自己的工作经验和成果与团队成员分享交流，共同促进团队整体水平的提升。

// 总之，我将以更加饱满的热情和更加务实的态度投入到未来的工作中去，为公司的发展贡献自己的力量。
// \`\`\``,
            programHtmlContent: '',
// `<h2>一、工作回顾</h2>
// <p>在过去的一段时间里，我致力于高效完成各项工作任务，确保每一项工作都能达到既定的标准和要求。通过不断学习和实践，我在专业技能和综合素质上均取得了显著提升。</p>
// <h3>（一）项目执行情况</h3>
// <ol>
// <li><p><strong>项目A</strong>：作为核心成员，我全程参与了项目A的规划、实施与收尾工作。在项目执行过程中，我积极沟通协调，确保项目按计划顺利推进。通过团队的努力，项目A最终成功交付，并获得了客户的高度评价。</p>
// </li>
// <li><p><strong>项目B</strong>：针对项目B的复杂性和紧迫性，我主动承担起了关键任务。通过深入分析项目需求，我制定了详细的工作计划，并带领团队高效执行。在项目遇到挑战时，我能够迅速调整策略，确保项目按时按质完成。</p>
// </li>
// </ol>
// <h3>（二）技能提升与学习</h3>
// <ol>
// <li><p><strong>专业技能</strong>：为了更好地适应工作需求，我不断学习和掌握新技能。通过参加专业培训、阅读专业书籍和在线课程，我在XX领域取得了显著进步，为工作的顺利开展提供了有力支持。</p>
// </li>
// <li><p><strong>综合素质</strong>：在工作中，我注重培养自己的综合素质。通过参与团队建设、沟通协调和解决问题等实践活动，我的团队协作能力、沟通能力和应变能力均得到了显著提升。</p>
// </li>
// </ol>
// <h2>二、工作反思</h2>
// <p>在回顾过去的工作时，我也深刻认识到自己存在的不足和需要改进的地方。</p>
// <h3>（一）存在的问题</h3>
// <ol>
// <li><p><strong>时间管理</strong>：在部分项目中，由于时间管理不当，导致部分工作进度滞后。这在一定程度上影响了项目的整体进度和效率。</p>
// </li>
// <li><p><strong>沟通效率</strong>：在团队沟通中，有时存在信息传递不畅或理解偏差的情况。这在一定程度上影响了团队的协作效率和工作质量。</p>
// </li>
// </ol>
// <h3>（二）改进措施</h3>
// <ol>
// <li><p><strong>优化时间管理</strong>：制定更加合理的时间计划表，明确各项工作的优先级和完成时间。同时，加强自我监督和管理，确保工作按计划有序进行。</p>
// </li>
// <li><p><strong>提升沟通效率</strong>：加强团队之间的沟通协作，确保信息传递的准确性和及时性。同时，注重沟通技巧和方法的学习和运用，提高沟通效率和质量。</p>
// </li>
// </ol>
// <h2>三、未来展望</h2>
// <p>展望未来，我将继续秉承敬业、专业、创新的精神，不断提升自己的综合素质和专业技能。同时，我也将积极适应公司的发展需求和市场变化，为公司的发展贡献自己的力量。</p>
// <h3>（一）个人发展规划</h3>
// <ol>
// <li><p><strong>深化专业技能</strong>：继续深入学习和掌握XX领域的专业知识和技能，提高自己的专业素养和竞争力。</p>
// </li>
// <li><p><strong>拓宽知识领域</strong>：关注行业动态和前沿技术发展趋势，积极拓宽自己的知识领域和视野。</p>
// </li>
// </ol>
// <h3>（二）团队贡献</h3>
// <ol>
// <li><p><strong>加强团队协作</strong>：积极参与团队建设活动，加强与团队成员之间的沟通和协作，提高团队的凝聚力和战斗力。</p>
// </li>
// <li><p><strong>分享经验成果</strong>：将自己的工作经验和成果与团队成员分享交流，共同促进团队整体水平的提升。</p>
// </li>
// </ol>
// <p>总之，我将以更加饱满的热情和更加务实的态度投入到未来的工作中去，为公司的发展贡献自己的力量。</p>
// `,     
            checkMdContent: '',
// `
// # 标题一
// 内容一人工智能是人类的语音内容一人工智能是xxxxxxxxx内容一人工智能是人类的语音内容一人工智能是xxxxxxxxx内容一人工智能是人类的语音内容一人工智能2是xxxxxxxxx内容一人工智能是人类的语音内容一人工智能是xxxxxxxxx内容一人工智能是人类的语音内容一人工智能是xxxxxxxxx内容一人工智能是人类的语音内容一人工智能是xxxxxxxxx内容一人工智能是人类的语音内容一人工智能是xxxxxxxxx内容一人工智能是人类的语音内容一人工智能是xxxxxxxxx内容一人工智能是人类的语音内容一人工智能是xxxxxxxxx内容一人工智能是人类的语音内容一人工智能是xxxxxxxxx内容一人工智能是人类的语音内容一人工智能是xxxxxxxxx内容一人工智能是人类的语音内容一人工智能是xxxxxxxxx内容一人工智能是人类的语音内容一人工智能是xxxxxxxxx内容一人工智能是人类的语音内容一人工智能是xxxxxxxxx内容一人工智能是人类的语音内容一人工智能是xxxxxxxxx内容一人工智能是人类的语音内容一人工智能是xxxxxxxxx内容一人工智能是人类的语音内容一人工智能是xxxxxxxxx内容一人工智能是人类的语音1内容一人工智能是xxxxxxxxx
// ## 标题二
// 这个妹妹很骚包
// ### 标题三
// 这篇文章写的很犀利
// 1.列表一
// 2.列表二
// 3.列表三
// #### 标题四
// - First item
// - Second item
// - Third item`,
            checkHtmlContent: '',
            //显示续写扩写弹出框
            showExConPo: false,
            //续写扩写润色标题
            writeTitle:'',
            mOrCTitle: '',
            //点击一键更正或取消提示
            mOrCMsg: '',
            showMDialog: false,
            showNDialog: false,
            generating: true,
            errorCount: 0,
            //校核类型列表
            defErrorList: [
                {
                    id: 1, 
                    title: '字词错误', 
                    type: 1, 
                    count: 0, 
                    data: [
                        // {id: '1', cont: '人工智能2', rightCont:'脑残智能', start: 92, end: 97},
                        // {id: '2', cont: '人类的语音1', rightCont:'人类的语言', start: 525, end: 531},
                    ]
                },
                { 
                    id: 2, 
                    title: '标点错误', 
                    type: 2, 
                    count: 0,
                    data: [
                        // {id: '1', cont: ',', rightCont:'，', start: 1, end: 6},
                        // {id: '2', cont: '慧演', rightCont:'慧眼', start: 12, end: 14},
                        // {id: '2', cont: '慧演', rightCont:'慧眼', start: 12, end: 14},
                    ]
                },
                {
                    id: 3, 
                    title: '语法错误', 
                    type: 3, 
                    count: 0,
                    data: [
                        // {id: '1', cont: '人类的语音', rightCont:'人类的语言', start: 1, end: 6},
                        // {id: '2', cont: '慧演', rightCont:'慧眼', start: 12, end: 14}
                    ]
                },
                { 
                    id: 4, 
                    title: '语句润色', 
                    type: 4, 
                    count: 0,
                    data: [
                        // {id: '1', cont: '人类的语音', rightCont:'人类的语言', start: 1, end: 6},
                        // {id: '2', cont: '慧演', rightCont:'慧眼', start: 12, end: 14}
                    ]
                }
            ],
            errorList: this.defErrorList,
            errContList: [],
            updateError: {},
            //当前错误类型
            errorSel:'',
            showErrDialog: false,
            //文件上传
            //0-首页上传，1-扩写等上传
            fileType: 0,
            improveFile: {},
            progressBar: false,
            disabledInp: false,
            fileName: '',
            // 设置每个分片的大小（字节）
            CHUNK_SIZE: 5 * 1024 * 1024 + "", // 1MB
            retryNum: 0,
            myindex: -1,
            fileSuffixs: ["doc", "docx"],
            pdfAndImgSuffixs: ["pdf", "jpg", "jpeg", "png", "bmp"],
            pdfSuffix: ['pdf'],
            imgSuffix: ["jpg", "jpeg", "png", "bmp"],
            showErrList: false,
            //语音
            voiceType: 0, //0:没有录音,1:主题,2:内容要求
            subjectTalking: false,
            MODEL_CODE: '1888', 
            CAPACITY_CODE: '010115',
            LANG: 'zh',
            WS_URL: '',
            checkSwitch: false,
            VoiceItemID: generateUUID(),
            count: 0,
            checkClick: 1,
            bufferData: [],
            voiceTxt:{
                ind: '',
                old: ''
            },
            myWebsocket: null,
            //展示定位弹窗
            showPositionDialog: false,
            //编辑
            showEditDialog: false,
            //编辑生成内容
            editGenCont: '',
            //编辑中的内容
            tempEditGenCont: '',
            actions:[{ text: '编辑' }],
            //需要添加监听事件的元素
            addElementList: ['h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'p', 'li'],
            
            //ppt模板弹窗
            showPptDialog: false,
            //ppt生成对象
            pptForm: {
                //标题
                title: '',
                //ppt模板
                modelId: ''
            },
            //通用模板
            pptComModelList:[{id:'1',logo:'../images/ppt/ppt-common1.png'},
                {id:'2',logo:'../images/ppt/ppt-common2.png'},
                {id:'3',logo:'../images/ppt/ppt-common1.png'},
                {id:'4',logo:'../images/ppt/ppt-common1.png'}],
                
            //专用模板
            pptDedModelList:[{id:'5',logo:'../images/ppt/ppt-common1.png'},
                {id:'6',logo:'../images/ppt/ppt-common2.png'},
            ],

            //流式输出显示控制
            chatTimer: null,
            chatBuffer: [],
            chatEnd: true,

            //底部生成大纲按钮是否显示
            bottomShow: true,

            voiceNoteId: null,
        }
    },
    watch: {
        streaming: {
            handler(newValue, oldValue) {
                this.changeMultiBtn = !newValue
            },
            immediate: true
        },
    },
    created() {
        const _this = this
        let jsApiList = []
        $.getScript("../../../js/jweixin-sgccigw-1.0.0.js" /*"js/jweixin-1.0.0.js"*/, function () {
            'use strict';
            wx.ready(function () {
                wx.onHistoryBack(() => {
                    _this.home()
                    return false
                })
            });
            jsApiList = [
                'startRecord',
                'stopRecord',
                'onVoiceRecordEnd',
                'translateVoice',                
                'previewFile',
                'startRecordVoiceBuffer',
                'ext_AudioRecorder_Start',
                'ext_AudioRecorder_Stop',
                'onRecordBufferReceived',
                'multiWindows_subscribe',
                'stopRecord',
                'onHistoryBack',
            ];
            wx.config({
                beta: true, // 调用wx.invoke形式的接口值时，该值必须为true。
                debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
                appId: corpid,
                timestamp: '1626832073',
                nonceStr: nonceStr,
                signature: signature,
                jsApiList: jsApiList
            });
        });
    },
    mounted() {
        this.compatibleInput()
        this.getTemplateList()

        this.addPopoverClick()

        window.addEventListener('resize', this.handleResize())
        // this.addClickEvent()
        // this.handleScrollBottom('contentRef')
        // this.addScrollEvent()
        //TODO 从缓存中获取主题以及文件信息
        let subjectTitle = ''
        let fileInfo = JSON.parse(sessionStorage.getItem('minutes_fileInfo'))
        let filSuffix = ['mp3', 'wav', 'amr', 'm4a', "docx", "doc"]
        
        console.log("minutes_fileInfo", fileInfo)
        if(fileInfo){
            let suffixs = fileInfo.fileName.split('.')
            subjectTitle = this.removeAllSuffixes(fileInfo.fileName, filSuffix)
            if(fileInfo.fileName.indexOf(".docx") < 0) {
                fileInfo.fileName = fileInfo.fileName + '.docx'
            }
            fileInfo.size = fileInfo.fileSize
            this.form.recordFile = fileInfo
            if(fileInfo.fileSize) {
                this.form.recordFile.fileSize = calcFileSize(this.form.recordFile.fileSize)
            }
            // if(suffixs.length > 1) {
            //     if(filSuffix.includes(suffixs[1].toLocaleLowerCase())){
            //         subjectTitle = suffixs[0]
            //     }
            // }
            this.voiceNoteId = fileInfo.dataId
        }
        if(subjectTitle){
            this.form.subjectTitle = subjectTitle
        }
        sessionStorage.removeItem('minutes_subjectTitle')
        sessionStorage.removeItem('minutes_fileInfo')
        // this.form.notificationFile = {
        //     "id": "1",
        //     "fileName": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.pdf",
        //     "type": "PDF",
        //     "img": "pdf",
        //     "fileSize": 878
        // }

        // this.currentStep = 2
        // this.improveFile = {
        //     "id": "1",
        //     "fileName": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.docx",
        //     "type": "word",
        //     "img": "word",
        //     "fileSize": '878KB',
        //     "size": 878
        // }
        // this.currentStep = 5
        // this.wordResult = {
        //     "id": "1",
        //     "fileName": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.docx",
        //     "type": "WORD",
        //     "img": "word",
        //     "fileSize": '878KB',
        //     "size": 878
        // }
        // this.pptLoading = true
        // this.pptResult = {
        //     id: '2'
        // }
    },
    methods: {
        removeAllSuffixes(str, suffixes) {
            const regex = new RegExp(`\\.(${suffixes.join('|')})$`, 'i');
            const newStr = str.replace(regex, '');
            // 如果替换后字符串变化了，继续处理
            return newStr === str ? newStr : this.removeAllSuffixes(newStr, suffixes);
        },
        handleResize(){
            this.$nextTick(()=>{
                var originalHeight=document.documentElement.clientHeight ||document.body.clientHeight;
                window.onresize = () => {
                    var resizeHeight=document.documentElement.clientHeight || document.body.clientHeight;
                    if(resizeHeight<originalHeight){
                        this.bottomShow = false
                    } else {
                        this.bottomShow = true
                    }
                }
            })
        },
        handleInputFocus() {
            if(!this.voiceType) {
                this.bottomShow = false
            }
        },
        handleInputBlur() {
            this.bottomShow = true
        },
        delFile(type) {
            if(0 == type) {
                this.form.notificationFile = {}
            }else if(1 == type) {
                this.improveFile = {}
            }else if(2 == type) {
                this.form.recordFile = {}
            }
        },
        getTemplateList() {
            const userId = sessionStorage.getItem("userId");
            let param = {
                "userId": userId,
                "type": 4, //this.writingType,
                "timestamp": new Date().getTime() + "",
            };
            let AuthenticationSession = sessionStorage.getItem("Authentication");
            data = JSON.stringify(param)
            let sign = sm3(data);
            $.ajax({
                url: localUrlLink + iscp_port + "/tjAiAssistant/template/getTemplateList",
                type: "post",
                async: true, //是否同步，false表示同步请求
                dataType: "json",
                data: data,
                headers: {
                    "Content-Type": "application/json;charset=UTF-8",
                    Authentication: AuthenticationSession,
                    sign: sign
                },
                success: (res, txt, xhr) => {
                    if (sm3(res.resultValueStr) == xhr.getResponseHeader("sign")) {
                        let Authentication = xhr.getResponseHeader("Authentication")
                        if (res.code == 200) {
                            if (Authentication) {
                                sessionStorage.setItem("Authentication", Authentication);
                            }
                            this.modelImages = []
                            this.modelList = res.resultValue
                            if(this.modelList && 0 < this.modelList.length) {
                                this.curModelId = this.modelList[0].id
                                this.modelList.forEach(item => {
                                    this.modelImages.push(item.img)
                                })
                            }
                        } else {
                            mui.toast('请稍后再试', {
                                duration: 1000,
                                type: 'div'
                            })
                        }
                    }
                },
                error: (e) => {
                    $(".curtain").css("display", "none");
                    mui.toast('请稍后再试', {
                        duration: 1000,
                        type: 'div'
                    })
                },
            });
        },
        markdown2Html(tmd) {
            let md = tmd.replace(/\`\`\`markdown/g, '').replace(/\`\`\`/g, '').replace(/\\n/g, "\n").replace(/\n/g, "  \n\n")
            
            try{
                md = decodeURIComponent(md)
            }catch (error) {
                md = md
            }
            if(0 < this.errContList.length) {
                // let _md = tmd.replace(/\n/g, "\n\n")
                //复制错误列表，倒序排列
                let _errContList = this.errContList.slice().reverse()
                console.log("原md内容", tmd)
                _errContList.forEach(item => {
                    tmd = replaceCharAt(tmd, 'replace_' + item.id + "_replace", item.start, item.end, item.cont)
                })
                
                tmd = tmd.replace(/\`\`\`markdown/g, '').replace(/\`\`\`/g, '').replace(/\\n/g, "\n").replace(/\n\n/g, " \n\n")
                console.log("替换后的md内容", tmd)
                let html = marked.parse(tmd)
                console.log("md转成的html", html)
                this.errContList.forEach(item => {
                    html = html.replace('replace_' + item.id + "_replace", 
                        "<span id='replace"+item.id+"' class='err-txt'>" + item.cont + "</span>")
                })
                console.log("替换后的html", html)
                return html
            }else {
                return marked.parse(md)
            }
        },
        //选择模板
        selModel(item) {
            if(this.curModelId == item.id) {
                //当前已选中
                this.modelImages = [item.img]
                this.modelImageShow = true
            }else {
                this.curModelId = item.id;
            }
        },
        handleTouchStart(event, item) {
            this.touchTimer = setTimeout(() => {
                this.modelImageShow = true
            }, 500);
        },
        handleTouchEnd(event, item) {
            this.touchTimer = clearTimeout(this.touchTimer)
            console.log("长按结束")
        },
        onImageChange(index) {
            this.modelImageIndex = index
        },
        //生成大纲
        genProgram() {
            if('' == this.form.subjectTitle) {
                $(".curtain").css("display", "none");
                mui.toast('请填写主题', {
                    duration: 'long',
                    type: 'div'
                })
                return false
            }
            if('' == this.curModelId) {
                $(".curtain").css("display", "none");
                mui.toast('请选择模板', {
                    duration: 'long',
                    type: 'div'
                })
                return false
            }
            //TODO 生成大纲后台请求
            const userId = sessionStorage.getItem("userId");
            let param = {
                "userId": userId,
                "subjectTitle": this.form.subjectTitle,
                "curModelId": this.curModelId,
                "materialList": this.materialList.map(file => file.id).join(","),
                "type": this.writingType, //工作方案
                "modelType": getLargeModelType(),
                "timestamp": new Date().getTime() + "",
            };
            $(".curtain").css("display", "block");
            this.currentStep = this.currentStep + 1
            
            this.chatTimer = clearIntervalTimer(this.chatTimer)
            this.abortCtrl = streamChat(localUrlLink + iscp_port + "/tjAiAssistant/writing/genOutline", param,
                (res) => {
                    this.streaming = true
                    $(".curtain").css("display", "none");
                    //成功回调
                    console.log(res)
                    if(200 == res.code) {
                        let result = res.resultValue
                        this.infSessionId = result.sessionId

                        this.chatEnd = false
                        if(!this.chatTimer) {
                            let interval = Math.floor(Math.random() * (150)) + 50;
                            this.chatTimer = setInterval(() => {
                                if(this.chatBuffer && 0 < this.chatBuffer.length) {
                                    let wordCount = Math.floor(Math.random() * (3)) + 1;
                                    let word = this.chatBuffer.splice(0, wordCount)

                                    this.outLineMdContent += word.join("")
                                    // 将Markdown转换为HTML
                                    this.outLineContent = this.markdown2Html(this.outLineMdContent)
                                    this.handleScrollBottom('outlineRef')
                                }
                                //输出完成,清除定时器
                                if(0 == this.chatBuffer.length && this.chatEnd) {
                                    mui.toast("生成大纲完成", { duration: "long", type: "div" });
                                    this.chatTimer = clearIntervalTimer(this.chatTimer)
                                }
                            }, interval);
                        }

                        this.chatBuffer.push(result.content)
                    }else {
                        //请求异常
                        this.chatEnd = true
                        mui.toast("生成大纲异常", { duration: "long", type: "div" });
                    }
                }, (err) => {
                    //失败回调
                    this.chatEnd = true
                    $(".curtain").css("display", "none");
                    mui.toast("生成大纲异常", { duration: "long", type: "div" });
                }, e => {
                    //请求完成
                    this.chatEnd = true
                    $(".curtain").css("display", "none");
                });
        },
        validForm() {
            if(!this.form.subjectTitle) {
                mui.toast("请填写主题", { duration: "long", type: "div" });
                return false
            }
            if(!this.form.recordFile.id) {
                mui.toast("请上传会议记录", { duration: "long", type: "div" });
                return false
            }
            return true
        },
        genContent(param) {
            if(!this.validForm()) {
                return
            }
             $(".curtain").css("display", "block");
            //TODO 生成内容后台请求
            const userId = sessionStorage.getItem("userId");

            let pEle = null
            if('contentGen' == this.quickSel) {
                pEle = document.getElementById(this.curPId)
            }else {
                param = {
                    "userId": userId,
                    "subjectTitle": this.form.subjectTitle,
                    "curModelId": this.curModelId,
                    "materialList": this.form.recordFile.id,
                    "highlight": this.form.highlight,
                    "type": this.writingType, //会议纪要
                    "timestamp": new Date().getTime() + "",
                };
                if(this.form.recordFile.id) {
                    param['notification'] = this.form.notificationFile.id
                }
                this.currentStep = this.currentStep + 1
            }
            param["modelType"] = getLargeModelType()
            $(".curtain").css("display", "block");
            
            // this.chatTimer = clearIntervalTimer(this.chatTimer)
            this.abortCtrl = streamChat(localUrlLink + iscp_port + "/tjAiAssistant/writing/genContent", param,
                (res) => {
                    //成功回调
                    // console.log(res)
                    this.streaming = true
                    $(".curtain").css("display", "none");
                    if(200 == res.code) {
                        let result = res.resultValue
                        this.infSessionId = result.sessionId
                        
                        // this.chatEnd = false
                        // if(!this.chatTimer) {
                        //     let interval = Math.floor(Math.random() * (150)) + 50;
                        //     this.chatTimer = setInterval(() => {
                        //         if(this.chatBuffer && 0 < this.chatBuffer.length) {
                        //             let wordCount = Math.floor(Math.random() * (3)) + 1;
                        //             let word = this.chatBuffer.splice(0, wordCount)

                        //             this.programMdContent += word.join("")
                        //             // 将Markdown转换为HTML
                        //             this.programHtmlContent = this.markdown2Html(this.programMdContent)
                        //             this.handleScrollBottom('contentRef')
                                    
                        //         }
                        //         //输出完成,清除定时器
                        //         if(0 == this.chatBuffer.length && this.chatEnd) {
                        //             this.addClickEvent()
                        //             this.addScrollEvent()
                        //             mui.toast("生成内容完成", { duration: "long", type: "div" });
                        //             this.chatTimer = clearIntervalTimer(this.chatTimer)
                        //         }
                        //     }, interval);
                        // }

                        // this.chatBuffer.push(result.content)

                        if('contentGen' == this.quickSel && null != pEle) {
                            this.replaceContent += result.content
                            pEle.innerHTML = this.markdown2Html(this.replaceContent)

                            this.$nextTick(() => {
                                let scrollElem = this.$refs['contentRef'];
                                if(scrollElem) {
                                    scrollElem.scrollTo({ top: pEle.scrollHeight, behavior: 'smooth' })
                                }
                            })

                        }else {
                            this.programMdContent += result.content
                            // 将Markdown转换为HTML
                            this.programHtmlContent = this.markdown2Html(this.programMdContent)
                            this.handleScrollBottom('contentRef')
                        }
                        
                        if(result.end) {
                            this.replaceContent = ''
                            // this.abortCtrl.abort()
                        }
                    }else {
                        //请求异常
                        // this.chatEnd = true
                        this.streaming = false
                        mui.toast("生成内容异常", { duration: "long", type: "div" });
                    }
                }, (err) => {
                    //失败回调
                    // this.chatEnd = true
                    this.streaming = false
                    $(".curtain").css("display", "none");
                    mui.toast("生成内容异常", { duration: "long", type: "div" });
                }, res => {
                    // this.chatEnd = true
                    if(this.streaming) {
                        mui.toast("生成内容完成", { duration: "long", type: "div" });
                    }
                    this.streaming = false
                    this.addClickEvent()
                    this.addScrollEvent()
                    $(".curtain").css("display", "none");
                });
        },
        handleImproveTalk() {
            if(!this.curPId) {
                mui.toast("请选择修改内容", { duration: "long", type: "div" });
                return
            }
            this.startTalk(3)
        },
        //生成内容重新、扩写、续写、润色
        genImprove() {
            this.stopTalk()
            if(!this.curPId) {
                mui.toast("请选择修改内容", { duration: "long", type: "div" });
                return
            }
            if(!this.quickSel) {
                mui.toast("请先选择扩写、续写或润色", { duration: "long", type: "div" });
                return
            }
            this.replaceContent = ''
            this.replaceHtmlContent = ''
            this.generating = true
            this.showExConPo = true
            $(".curtain").css("display", "block");
            //TODO 扩写、续写、润色后台请求
            const userId = sessionStorage.getItem("userId");
            let param = {
                "userId": userId,
                "subjectTitle": this.form.subjectTitle,
                "curModelId": this.curModelId,
                "materialList": this.materialList.map(file => file.id).join(","),
                "type": this.writingType, //工作总结
                "outline": this.outLineMdContent,
                //文档内容
                "content": html2Md(this.programHtmlContent),
                 //扩写、续写、润色
                "improveType": this.quickSel,
                //选择的内容--待优化的内容
                "improveContent": document.getElementById(this.curPId).innerText,
                //待优化的要求，文本框输入的
                "improveNeed": this.requireText,
                //上传的文件
                "improveFile": this.improveFile.id,
                "timestamp": new Date().getTime() + "",
            };

            if('contentGen' == this.quickSel){
                let pEle = document.getElementById(this.curPId)
                if(pEle) {
                    this.form.contentNeed = "请对以下内容重新生成：\n" + html2Md(pEle.innerHTML)
                }
                param = {
                    "userId": userId,
                    "sessionId": this.infSessionId,
                    "subjectTitle": this.form.subjectTitle,
                    "curModelId": this.curModelId,
                    "contentNeed": this.form.contentNeed,
                    "materialList": this.improveFile.id,
                    "type": this.writingType, //工作总结
                    "timestamp": new Date().getTime() + "",
                };
                this.genContent(param)
                return
            }

            param["modelType"] = getLargeModelType()
            // this.chatTimer = clearIntervalTimer(this.chatTimer)
            this.abortCtrl = streamChat(localUrlLink + iscp_port + "/tjAiAssistant/writing/genImprove", param,
                (res) => {
                    $(".curtain").css("display", "none");
                    this.requireText = ''
                    //成功回调
                    console.log(res)
                    if(200 == res.code) {
                        let result = res.resultValue

                        // this.chatEnd = false
                        // if(!this.chatTimer) {
                        //     let interval = Math.floor(Math.random() * (150)) + 50;
                        //     this.chatTimer = setInterval(() => {
                        //         if(this.chatBuffer && 0 < this.chatBuffer.length) {
                        //             let wordCount = Math.floor(Math.random() * (3)) + 1;
                        //             let word = this.chatBuffer.splice(0, wordCount)

                        //             this.replaceContent += word.join("")
                        //             this.replaceHtmlContent = this.markdown2Html(this.replaceContent)
                        //             this.handleScrollBottom('improveRef')
                        //         }
                        //         //输出完成,清除定时器
                        //         if(0 == this.chatBuffer.length && this.chatEnd) {
                        //             this.chatTimer = clearIntervalTimer(this.chatTimer)
                        //         }
                        //     }, interval);
                        // }

                        // this.chatBuffer.push(result.content)

                        this.replaceContent += result.content
                        this.replaceHtmlContent = this.markdown2Html(this.replaceContent)
                        this.handleScrollBottom('improveRef')
                    }else {
                        //请求异常
                        // this.chatEnd = true
                        let msg = "expand"==this.quickSel ? "扩写" : ("continued"==this.quickSel ? "续写" : "润色")
                        mui.toast(msg + "异常", { duration: "long", type: "div" });
                    }
                }, (err) => {
                    //失败回调
                    // this.chatEnd = true
                    $(".curtain").css("display", "none");
                    let msg = "expand"==this.quickSel ? "扩写" : ("continued"==this.quickSel ? "续写" : "润色")
                    mui.toast(msg + "异常", { duration: "long", type: "div" });
                }, e => {
                    //请求完成
                    // this.chatEnd = true
                    $(".curtain").css("display", "none");
                    this.generating = false
                });
        },
        //文档校核
        contentCheck() {
            //TODO 文档校核后台请求
            $(".curtain").css("display", "block");
            const userId = sessionStorage.getItem("userId");
            let param = {
                "userId": userId,
                "subjectTitle": this.form.subjectTitle,
                "curModelId": this.curModelId,
                "materialList": this.materialList.map(file => file.id).join(","),
                "type": this.writingType, //工作总结
                "modelType": getLargeModelType(),
                "outline": this.outLineMdContent,
                //文档内容
                "content": html2Md(this.programHtmlContent),
                "timestamp": new Date().getTime() + "",
            };
            this.errorCount = 0
            this.currentStep = this.currentStep + 1
            this.abortCtrl = streamChat(localUrlLink + iscp_port + "/tjAiAssistant/writing/contentCheck", param,
                (res) => {
                    $(".curtain").css("display", "none");
                    $('#checkDiv').css("display", "block");
                    //成功回调
                    console.log(res)
                    if(200 == res.code) {
                        let result = res.resultValue
                        
                        this.checkMdContent = result.originalText
                        console.log(result.originalText)
                        this.checkHtmlContent = this.markdown2Html(result.originalText) //this.programHtmlContent
                        this.errorList = result.errorList
                        this.errorList.forEach(item => {
                            this.errorCount += item.count
                        })
                        this.handleScrollBottom('checkRef')
                    }else {
                        //请求异常
                        mui.toast("生成内容异常", { duration: "long", type: "div" });
                    }
                }, (err) => {
                    //失败回调
                    $(".curtain").css("display", "none");
                    mui.toast("生成内容异常", { duration: "long", type: "div" });
                }, (res) => {
                    $(".curtain").css("display", "none");
                });
        },
        //生成总结
        createDoc() {
            setTimeout(() => {
                const userId = sessionStorage.getItem("userId");
                let param = {
                    "userId": userId,
                    "subjectTitle": this.form.subjectTitle,
                    "voiceNoteId": this.voiceNoteId,
                    "curModelId": this.curModelId,
                    "materialList": this.materialList.map(file => file.id).join(","),
                    "type": this.writingType, //会议纪要
                    "modelType": getLargeModelType(),
                    "outline": this.outLineMdContent,
                    //文档内容
                    "content": this.checkMdContent ? html2Md(this.checkHtmlContent) : html2Md(this.programHtmlContent),
                    "timestamp": new Date().getTime() + "",
                };
                let AuthenticationSession = sessionStorage.getItem("Authentication");
                data = JSON.stringify(param)
                let sign = sm3(data);
                $.ajax({
                    url: localUrlLink + iscp_port + "/tjAiAssistant/writing/createDoc",
                    type: "post",
                    async: false, //是否同步，false表示同步请求
                    dataType: "json",
                    data: data,
                    headers: {
                        "Content-Type": "application/json;charset=UTF-8",
                        Authentication: AuthenticationSession,
                        sign: sign
                    },
                    success: (res, txt, xhr) => {
                        $(".curtain").css("display", "none");
                        // { id: '1', fileName: '人工智能：塑造未来的技术力量.docx', type: 'word', fileSize: '126.35KB' },
                        if (res.code == 200) {
                            this.$set(this.wordResult, 'id', res.resultValue.id)
                            this.wordResult['fileName'] = res.resultValue.name
                            this.wordResult['type'] = 'word'
                            this.wordResult['size'] = res.resultValue.size
                            this.wordResult['fileSize'] = calcFileSize(res.resultValue.size)
                        } else {
                            mui.toast('请稍后再试', {
                                duration: 1000,
                                type: 'div'
                            })
                        }
                        // this.currentStep = this.currentStep + 1
                    },
                    error: (e) => {
                        $(".curtain").css("display", "none");
                        mui.toast('请稍后再试', {
                            duration: 1000,
                            type: 'div'
                        })
                    },
                });
            }, 1000);
        },
        //上一步
        preStep(){
            if(this.streaming) {
                mui.toast('生成中不能跳转', {
                    duration: 1000,
                    type: 'div'
                })
                return
            }
            if(this.abortCtrl) {
                this.stopGen()
            }
            this.showErrDialog = false;
            if(2 == this.currentStep){
                this.outLineContent = ''
                this.currentStep = this.currentStep - 1
                $(location).attr("href", "../../hyzs.html");
            }else if(4 == this.currentStep){
                this.addClickEvent()
                this.handleScrollBottom('contentRef')
            }
            this.currentStep = this.currentStep - 1
        },
        //下一步
        nextStep() {
            if(this.streaming) {
                mui.toast('生成中不能跳转', {
                    duration: 1000,
                    type: 'div'
                })
                return
            }
            if(this.abortCtrl) {
                this.stopGen()
            }
            this.showErrDialog = false;
            if(2 == this.currentStep) {
                this.programMdContent = ''
                // 将Markdown转换为HTML
                this.programHtmlContent = ''
                this.stopTalk()
                //生成内容
                this.genContent()
            }
            // else if(3 == this.currentStep){
            //     $(".curtain").css("display", "none");
            //     var i = 0;
            //     mui.confirm("文档校核需要较长时间，是否跳过该步骤进入下一步", "文档校核", ["校核", "跳过"], (e) => {
            //         if (i > 0) return;
            //         i++;
            //         if (e.index == 1) {
            //             $(".curtain").css("display", "block");
            //             this.currentStep = this.currentStep + 1
            //             this.nextStep()
            //         } else {
            //             $(".curtain").css("display", "block");
            //             //文档校核
            //             this.checkMdContent = ''
            //             this.checkHtmlContent = ''
            //             this.errorList = this.defErrorList
            //             this.contentCheck()
            //         }
            //     });
            // }
            else if(3 == this.currentStep) {
                 $(".curtain").css("display", "block");
                //创建文档
                // setTimeout(() => {
                    sessionStorage.removeItem('voiceId')
                    this.currentStep += 2
                    $(".curtain").css("display", "none");
                    this.createDoc()
                // }, 1000);
            }
        },
        //关闭编辑
        closePopOver(){
            if(!this.quickSel) {
                //移除所有的edit样式
                let pEle = document.getElementById(this.curPId)
                if(pEle) {
                    pEle.classList.remove('p-edit')
                }
                return false;
            }
        },
        addScrollEvent() {
            // this.$nextTick(() => {

            //     let scrollElem = this.$refs['contentRef'];
            //     if(scrollElem) {
            //         scrollElem.addEventListener('scroll', (e) => {
            //             // 执行的具体操作
            //             if(this.curPId) {
            //                 let pElement = document.getElementById(this.curPId)
            //                 let popover = document.getElementById('myPopover')
            //                 popover.style.top = (pElement.offsetTop - scrollElem.scrollTop - popover.offsetHeight - 10) + 'px';
            //                 popover.style.left = pElement.offsetLeft + pElement.offsetWidth/2 - popover.offsetWidth/2 + 'px';
            //             }
            //         })
            //     }
            // })
        },
        addPopoverClick() {
            window.addEventListener('click', (event) => {
                event.preventDefault()
                let myPopover = document.getElementById('myPopover')
                if(myPopover) {
                    myPopover.style.display = 'none'
                }
            })
        },
        //添加点击事件
        addClickEvent(){
            setTimeout(()=>{
                this.$nextTick(() => {
                    // 获取div元素
                    var div = document.getElementById('step3-mdBody');
                    
                    this.addElementList.forEach((em) => {
                        // 获取div内的所有元素
                        var pItems = div.querySelectorAll(em);

                        // 添加事件监听器
                        pItems.forEach((pElement) => {
                            pElement.addEventListener('click', (event) => {
                                this.clickCallback(event, pElement, em)
                            });
                            // this.addUniversalLongPress(pElement, em, 1000)
                        });
                    })
                });
            },500)
            
        },
        addUniversalLongPress(element, em, duration) {
            let timer;
            
            duration = duration || 1000
            const start = (e) => {
                timer = setTimeout(() => {
                    e.preventDefault()
                    this.clickCallback(e, element, em)
                }, duration)
            };
            
            const cancel = () => clearTimeout(timer);
            
            // 触摸设备
            element.addEventListener('touchstart', start, { passive: true });
            element.addEventListener('touchend', cancel);
            element.addEventListener('touchcancel', cancel);
            
            // 鼠标设备
            element.addEventListener('mousedown', start);
            element.addEventListener('mouseup', cancel);
            element.addEventListener('mouseleave', cancel);
            
            element.addEventListener('touchmove', (e) => {
                const currentX = e.touches[0].clientX;
                const currentY = e.touches[0].clientY;
                
                // 如果移动距离超过 5px，取消长按
                if (Math.abs(currentX - startX) > 5 || Math.abs(currentY - startY) > 5) {
                    clearTimeout(timer);
                }
            });

            // 禁用上下文菜单
            element.addEventListener('contextmenu', (e) => e.preventDefault());
        },
        clickCallback(event, pElement, em) {
            //再次点击，取消编辑
            if(this.curPId && pElement.id == this.curPId) {
                var clsItems = document.querySelectorAll(".p-edit");
                if(clsItems){
                    clsItems.forEach((cItem) => {
                        cItem.classList.remove('p-edit')
                    })
                }
                // popover元素
                var popover = document.getElementById('myPopover');
                if(popover) {
                    popover.style.display = 'none';
                }
                this.curPId = ''
                this.quickSel=''
            }else {
                event.preventDefault()
                var clsItems = document.querySelectorAll(".p-edit");
                if(clsItems){
                    clsItems.forEach((cItem) => {
                        cItem.classList.remove('p-edit')
                    })
                }
                
                pElement.classList.add("p-edit"); // 增加class
                if(!pElement.id) {
                    pElement.id = 'md-'+em+'-' + new Date().getTime();
                }

                this.$nextTick(() => {
                    this.curPId = pElement.id

                    // popover元素
                    var popover = document.getElementById('myPopover');
                    // 设置popover的位置
                    let scrollElem = this.$refs['contentRef'];
                    
                    let header = document.getElementsByClassName('header_tit')[0]

                    let autoHeight = 10
                    if('block' == popover.style.display) {
                        autoHeight = 40
                    }

                    popover.style.top = (pElement.offsetTop - header.offsetHeight - autoHeight) + 'px';
                    popover.style.left = pElement.offsetLeft + pElement.offsetWidth/2 - 30 + 'px';
                    
                    popover.style.scrollTop = scrollElem.scrollTop
                    
                    // 显示popover
                    popover.style.display = 'block';

                    // 添加关闭popover的事件监听
                    popover.addEventListener('click', function() {
                        popover.style.display = 'none';
                    });
                })
            }

            event.stopPropagation()
        },
        handleEditPContent(){
            let pEle = document.getElementById(this.curPId)
            phtml = pEle.innerHTML
            // pEle.classList.remove('p-edit')
            this.showEditDialog = true
            this.editGenCont = phtml
            this.tempEditGenCont = phtml
        },
        //编辑大纲
        editoutLineContent() {
            this.canEditContent = true;
            //解决点击与滑动冲突
            this.$nextTick(()=>{
                // 假设有一个父元素 #parent 和多个子元素 .child
                const parent = document.getElementById('mdBody');
                
                // 标志位，初始化为false
                let isScrolling = false;
                // 触摸开始事件
                parent.addEventListener('touchstart', function(e) {
                    // 设置滑动标志位
                    isScrolling = true;
                });
                
                // 触摸结束事件
                parent.addEventListener('touchend', function(e) {
                    // 重置滑动标志位
                    isScrolling = false;
                });
                
                // 点击事件
                parent.addEventListener('click', function(e) {
                    // 只在非滑动状态下执行点击操作
                    if (!isScrolling) {
                        // 执行点击后的操作
                    }
                    // 阻止点击事件冒泡，防止影响滑动
                    e.stopPropagation();
                });
                
                // 滑动事件
                parent.addEventListener('touchmove', function(e) {
                    // 只在滑动状态下执行滑动操作
                    if (isScrolling) {
                        // 执行滑动后的操作
                    }
                    // 阻止滑动事件冒泡，防止影响点击
                    e.stopPropagation();
                });
            });


            this.editPContent = Object.assign(this.outLineContent)

            this.$nextTick(() => {
                document.getElementById('mdBody').addEventListener('keydown', function (event) {
                    if (event.key === 'Enter') {
                        const selection = getSelection()
                        // let titleNodeNames = ["h1", "h2", "h3", "h4", "h5", "h6", "li"];
                        // if(!titleNodeNames.includes(selection.focusNode.parentElement.nodeName).toLowerCase) {
                        //     event.preventDefault();
                        //     return;
                        // }
                        if (selection.focusOffset == getSelection().focusNode.length) {
                            event.preventDefault(); // 阻止默认行为，即不换行
                            var range, node;
                            // 获取已存在的div
                            const curNode = window.getSelection().focusNode;
                            // 创建新的div
                            var newH = document.createElement(window.getSelection().focusNode.parentElement.nodeName);

                            // 将新的div添加到已存在的div之后
                            curNode.parentNode.parentElement.insertBefore(newH, curNode.parentNode.nextSibling);

                            // 清除已有的选区
                            window.getSelection().removeAllRanges();

                            // 创建一个新的range对象
                            var range = document.createRange();
                            range.setStart(newH, 0); // index是你想要设置的光标位置

                            // 并将其添加到选区
                            var _selection = window.getSelection();
                            _selection.addRange(range);
                        }
                    }
                });
            })

        },
        //取消修改大纲
        cancleEdit() {
            this.canEditContent = false;
            //清除编辑数据
            this.editPContent = ''
        },
        //确认修改大纲
        confirmEdit() {
            this.canEditContent = false;
            let mdBody = document.getElementById('mdBody');
            this.outLineContent = mdBody.innerHTML;
            this.outLineMdContent = html2Md(this.outLineContent)
        },
        //选中续写等
        selQuickType(event, item) {
            if(!this.curPId) {
                mui.toast("请选择修改内容", { duration: "long", type: "div" });
            }else if(this.quickSel == item.type){
                this.quickSel = ''
                this.writeTitle = ''
            }else {
                this.quickSel = item.type
                // this.showExConPo = true
                this.writeTitle = item.title
            }
            event.preventDefault()
        },
        //停止生成
        stopGen(){
            this.generating = false;
            this.abortCtrl.abort()
        },
        //重写
        reGen() {
            this.genImprove()  
        },
        //取消替换
        contentCancle(){
            this.replaceHtmlContent = ''
            this.showExConPo = false;
        },
        //替换
        contentReplace() {
            let pEle = document.getElementById(this.curPId)
            if('p' == pEle.nodeName.toLocaleLowerCase()) {
                pEle.classList.remove('p-edit')
                let firstTagHtml = getFirstHtmlTag(this.replaceHtmlContent)
                firstTagHtml = firstTagHtml.substring(0, firstTagHtml.length-1)
                let addHtml = ' class="p-edit" id="' + this.curPId + '"'
                let endHtml = this.replaceHtmlContent.substring(firstTagHtml.length)
                let newHtml = firstTagHtml + addHtml + endHtml
                pEle.outerHTML = newHtml
            }else {
                pEle.innerHTML = this.replaceHtmlContent
            }

            this.programHtmlContent = document.getElementById('step3-mdBody').innerHTML
            this.programMdContent = html2Md(this.programHtmlContent)

            this.addClickEvent()

            this.curPId = ''
            this.quickSel = ''
            this.showExConPo = false
        },
        //错误类型选择
        selErrorType(item){
            this.showErrDialog = false
            if(!item.data || 0 == item.data.length) {
                return
            }
            this.$nextTick(()=>{
                this.errorSel = item.type;
                this.errTitle = item.title
                
                this.errContList = item.data
                if(this.errContList.length > 0){
                    this.showErrDialog = true 
                    //重新渲染成html
                    this.checkHtmlContent = this.markdown2Html(this.checkMdContent)
                }
            })
            
        },
        //定位到错误位置
        toErrorPos(item) {
            let element = document.getElementById('replace' + item.id)
            if (element) {
                element.scrollIntoView({ behavior: 'smooth' });
                this.showPositionDialog = true
                this.showErrDialog = false
                this.updateError = item
            }
        },
        handleEditError() {
            // 修改内容
            this.checkMdContent = replaceCharAt(this.checkMdContent, this.updateError.rightCont, this.updateError.start, this.updateError.end, this.updateError.cont)
            this.handleIgnoreError()
        },
        handleIgnoreError() {
            this.errContList = this.errContList.filter(item => item.id != this.updateError.id)
            this.errorList.forEach(item => {
                if(item.type == this.errorSel) {
                    item.data = item.data.filter(item => item.id != this.updateError.id)
                    item.count = item.data.length
                }
            })
            this.checkHtmlContent = this.markdown2Html(this.checkMdContent)
            this.closePositionDialog()
        },
        //关闭定位弹窗
        closePositionDialog(){
            this.showPositionDialog = false;
        },
        //一键修正确认
        mConfirm(){
            // 错误列表集合
            let _errContList = []
            this.errorList.forEach(item => {
                _errContList = _errContList.concat(item.data)
            })
            //倒序
            _errContList.sort((a,b) => {
                return b.start - a.start
            })
            //替换
            _errContList.forEach(error => {
                this.checkMdContent = replaceCharAt(this.checkMdContent, error.rightCont, error.start, error.end, error.cont)
            })
            this.errorList.forEach(item => {
                item.data = []
                item.count = 0
            })
            this.errContList = []
            this.checkHtmlContent = this.markdown2Html(this.checkMdContent)
            this.showErrDialog = false
        },
        //一键更正取消
        mCancle(){

        },
        //一键忽略确认
        nConfirm(){
            this.errorList.forEach(item => {
                item.data = []
                item.count = 0
            })
            this.errContList = []
            this.checkHtmlContent = this.markdown2Html(this.checkMdContent)
            this.showErrDialog = false
        },
        //一键忽略取消
        nCancle(){},
        //一键忽略
        neglectAll(){
            this.showNDialog = true
        },
        closeErrDialog(){
            this.showErrDialog = false
        },
        //编辑取消
        editCancle(){
            // this.curPId = ''
            this.editGenCont = ''
            this.showEditDialog = false
        },
        //修改内容
        changeCont(event){
            this.tempEditGenCont = event.target.innerHTML;
        },
        //编辑确认
        editConfirm(){
            let pEle = document.getElementById(this.curPId)
            // if(this.tempEditGenCont){
                pEle.innerHTML = this.tempEditGenCont
            // } else {
            //     pEle.innerHTML = this.editGenCont
            // }
            let _editGenCont = this.tempEditGenCont.replace(/\<br\>/g,'')
            if(!_editGenCont) {
                console.log('this.tempEditGenCont', this.tempEditGenCont)
                pEle.remove()
            }
            this.programHtmlContent = document.getElementById('step3-mdBody').innerHTML
            this.programMdContent = html2Md(this.programHtmlContent)
           
            this.addClickEvent()
            
            // this.curPId = ''
            this.showEditDialog = false
        },
        //一键修正
        modifyAll(){
            this.showMDialog = true
        },
        /**
         * 获取ppt模板
         */
        getPptModelList() {
            const userId = sessionStorage.getItem("userId");
            let param = {
                "userId": userId,
                "modelType": getLargeModelType(),
                "timestamp": new Date().getTime() + "",
            };
            let AuthenticationSession = sessionStorage.getItem("Authentication");
            data = JSON.stringify(param)
            let sign = sm3(data);
            $.ajax({
                url: localUrlLink + iscp_port + "/tjAiAssistant/ppt/getTemplatesList",
                type: "post",
                async: false, //是否同步，false表示同步请求
                dataType: "json",
                data: data,
                headers: {
                    "Content-Type": "application/json;charset=UTF-8",
                    Authentication: AuthenticationSession,
                    sign: sign
                },
                success: (res, txt, xhr) => {
                    if (res.code == 200) {
                        this.pptComModelList = res.resultValue.general;
                        this.pptDedModelList = res.resultValue.special;
                        this.showPptDialog = true
                        //TODO 加载专有模板与通用模板
                        this.pptForm.title = this.form.subjectTitle
                    } else {
                        mui.toast('请稍后再试', {
                            duration: 1000,
                            type: 'div'
                        })
                    }
                },
                error: (e) => {
                    $(".curtain").css("display", "none");
                    mui.toast('请稍后再试', {
                        duration: 1000,
                        type: 'div'
                    })
                },
            });
        },
        //打开ppt模板
        showPptSheet(wordResult) {
            this.getPptModelList()
            this.showPptDialog = true
            //TODO 加载专有模板与通用模板
            this.pptForm.title = this.form.subjectTitle
        },
        //选择ppt模板
        selPptModel(item){
            this.pptForm.modelId = item.id;
        },
        //生成ppt
        createPpt(){
            if(!this.pptForm.modelId) {
                mui.toast('请选择PPT模板', {
                    duration: 1000,
                    type: 'div'
                })
                return
            }
            if(!this.pptForm.title) {
                mui.toast('请填写文件标题', {
                    duration: 1000,
                    type: 'div'
                })
                return
            }
            $(".curtain").css("display", "block");
            const userId = sessionStorage.getItem("userId");
            let param = {
                "id": this.wordResult.writingId,
                "wordId": this.wordResult.id ? this.wordResult.id : "",
                "userId": userId,
                "modelId": this.pptForm.modelId,
                "modelType": getLargeModelType(),
                "subject": this.pptForm.title,
                "timestamp": new Date().getTime() + "",
            };
            let AuthenticationSession = sessionStorage.getItem("Authentication");
            data = JSON.stringify(param)
            let sign = sm3(data);

            this.abortCtrl = streamChat(localUrlLink + iscp_port + "/tjAiAssistant/writing/createPpt", param,
                (res) => {
                    //成功回调
                    // console.log(res)
                    $(".curtain").css("display", "none");
                    if (res.code == 200) {
                        this.pptResult = {
                            "id": res.resultValue.id,
                            "fileName": res.resultValue.name,
                            "type": 'ppt',
                            "size": res.resultValue.size,
                            "fileSize": calcFileSize(res.resultValue.size),
                        }
                        this.showPptDialog = false
                    } else {
                        mui.toast('请稍后再试', {
                            duration: 1000,
                            type: 'div'
                        })
                    }
                }, (err) => {
                    $(".curtain").css("display", "none");
                    mui.toast('请稍后再试', {
                        duration: 1000,
                        type: 'div'
                    })
                }, res => {
                    $(".curtain").css("display", "none");
                    mui.toast("PPT生成完成", { duration: "long", type: "div" });
                });
                
            // $.ajax({
            //     url: localUrlLink + iscp_port + "/tjAiAssistant/writing/createPpt",
            //     type: "post",
            //     async: false, //是否同步，false表示同步请求
            //     dataType: "json",
            //     data: data,
            //     headers: {
            //         "Content-Type": "application/json;charset=UTF-8",
            //         Authentication: AuthenticationSession,
            //         sign: sign
            //     },
            //     success: (res, txt, xhr) => {
            //         $(".curtain").css("display", "none");
            //         // this.pptResult = { id: '1', fileName: '人工智能：塑造未来的技术力量.ppt', type: 'ppt', fileSize: '120.85KB' }
            //         if (res.code == 200) {
            //             this.pptResult = {
            //                 "id": res.resultValue.id,
            //                 "fileName": res.resultValue.name,
            //                 "type": 'ppt',
            //                 "size": res.resultValue.size,
            //                 "fileSize": calcFileSize(res.resultValue.size),
            //             }
            //             this.showPptDialog = false
            //         } else {
            //             mui.toast('请稍后再试', {
            //                 duration: 1000,
            //                 type: 'div'
            //             })
            //         }
            //     },
            //     error: (e) => {
            //         $(".curtain").css("display", "none");
            //         mui.toast('请稍后再试', {
            //             duration: 1000,
            //             type: 'div'
            //         })
            //     },
            // });
        },
        //创建pdf
        createPdf(item) {
            if(!item.id) {
                return
            }
            if(this.pptResult.id) {
                return
            }
            // $(".curtain").css("display", "block");
            this.pptLoading = true
            const userId = sessionStorage.getItem("userId");
            let param = {
                "id": this.wordResult.writingId,
                "wordId": this.wordResult.id ? this.wordResult.id : "",
                "userId": userId,
                "type": this.writingType,
                "modelType": 'BAIDU', //getLargeModelType(),
                "timestamp": new Date().getTime() + "",
            };
            let AuthenticationSession = sessionStorage.getItem("Authentication");
            data = JSON.stringify(param)
            let sign = sm3(data);

            this.abortCtrl = streamChat(localUrlLink + iscp_port + "/tjAiAssistant/writing/createPdf", param,
                (res) => {
                    //成功回调
                    // console.log(res)
                    $(".curtain").css("display", "none");
                    if (res.code == 200) {
                        this.pptResult = {
                            "id": res.resultValue.id,
                            "fileName": res.resultValue.name,
                            "type": 'pdf',
                            "size": res.resultValue.size,
                            "fileSize": calcFileSize(res.resultValue.size),
                        }
                        this.handleScrollBottom('programMainRef')
                        mui.toast("PDF生成完成", { duration: "long", type: "div" });
                    } else {
                        mui.toast('请稍后再试', {
                            duration: 1000,
                            type: 'div'
                        })
                    }
                }, (err) => {
                    $(".curtain").css("display", "none");
                    mui.toast('请稍后再试', {
                        duration: 1000,
                        type: 'div'
                    })
                }, res => {
                    $(".curtain").css("display", "none");
                });
        },
        chooseUpload(type) {
            if(1 == type && !this.curPId) {
                mui.toast("请选择修改内容", { duration: "long", type: "div" });
                return
            }
            this.fileType = type

            let filePathList = this.$refs.chooseDirRef.filePathList
            if(localStorage.getItem("showBtn") == 'true' && filePathList.length >= 2 && !this.isflageIOX ){
                this.$refs.chooseDirRef.showFilepath = true
            }else {
                this.uploadFunc()
            }
        },
        chooseDirUpload(item) {
            if(item&&(item.id != 0)) {
                let _that = this
                wx.invoke("ext_FileBrowser_AppointDirChooseFile", 
                    {data : {"appointDirPath": item.pathName}}, 
                    (res) => {
                        _that.channelId = "writing_upload_" + createNonceStr(8) + new Date().getTime() + "";
                        console.log('res', res)
                        let recordArr = [{
                            name: res.name,
                            path: res.filePath,
                            fileSize: res.size
                        }]
                        const suffix = recordArr[0].name.split('.').reverse()[0]
                        if(!recordArr[0].fileSize) {
                            mui.toast('文件不能为空', {
                                duration: 'long',
                                type: 'div'
                            })
                            return
                        }
                        if(0 == _that.fileType) {
                            if (!_that.pdfAndImgSuffixs.includes(suffix.toLocaleLowerCase())) {
                                mui.toast('请选择PDF或图片', {
                                    duration: 'long',
                                    type: 'div'
                                })
                                return
                            }
                        }else if (!_that.fileSuffixs.includes(suffix.toLocaleLowerCase())) {
                            mui.toast('请选择WORD文档', {
                                duration: 'long',
                                type: 'div'
                            })
                            return
                        }
                        if (checkFileNameForSensitiveWords(recordArr[0].name)) {
                            mui.toast('检测到敏感内容，请确认后再试。', {
                                duration: 'long',
                                type: 'div'
                            })
                            return false
                        }
                        _that.checkList(recordArr[0].path, recordArr[0].name, _that.channelId, recordArr[0].fileSize)
                    })
            }else {
                this.uploadFunc()
            }
        },
        uploadFunc(type) {
            // if(1 == type && !this.curPId) {
            //     mui.toast("请选择修改内容", { duration: "long", type: "div" });
            //     return
            // }
            // this.fileType = type
            let _that = this
            wx.invoke("ext_FileBrowser_StartPreView", {}, function (res) {
                _that.channelId = "writing_upload_" + createNonceStr(8) + new Date().getTime() + "";

                if (_that.isflageIOX) {
                    const suffix = res.name.split('.').reverse()[0]
                    if(!res.size) {
                        mui.toast('文件不能为空', {
                          duration: 'long',
                          type: 'div'
                        })
                        return
                      }
                    if(0 == _that.fileType) {
                        if (!_that.pdfAndImgSuffixs.includes(suffix.toLocaleLowerCase())) {
                            mui.toast('请选择PDF或图片', {
                                duration: 'long',
                                type: 'div'
                            })
                            return
                        }
                    }else if (!_that.fileSuffixs.includes(suffix.toLocaleLowerCase())) {
                        mui.toast('请选择WORD文档', {
                            duration: 'long',
                            type: 'div'
                        })
                        return
                    }
                    if (checkFileNameForSensitiveWords(res.name)) {
                        mui.toast('检测到敏感内容，请确认后再试。', {
                            duration: 'long',
                            type: 'div'
                        })
                        return false
                    }
                    _that.checkList(res.filePath, res.name, _that.channelId, res.size)
                } else {
                    let recordArr = JSON.parse(res.result)
                    const suffix = recordArr[0].name.split('.').reverse()[0]
                    if(!recordArr[0].fileSize) {
                        mui.toast('文件不能为空', {
                            duration: 'long',
                            type: 'div'
                        })
                        return
                    }
                    if(0 == _that.fileType) {
                        if (!_that.pdfAndImgSuffixs.includes(suffix.toLocaleLowerCase())) {
                            mui.toast('请选择PDF或图片', {
                                duration: 'long',
                                type: 'div'
                            })
                            return
                        }
                    }else if (!_that.fileSuffixs.includes(suffix.toLocaleLowerCase())) {
                        mui.toast('请选择WORD文档', {
                            duration: 'long',
                            type: 'div'
                        })
                        return
                    }
                    if (checkFileNameForSensitiveWords(recordArr[0].name)) {
                        mui.toast('检测到敏感内容，请确认后再试。', {
                            duration: 'long',
                            type: 'div'
                        })
                        return false
                    }
                    _that.checkList(recordArr[0].path, recordArr[0].name, _that.channelId, recordArr[0].fileSize)
                }
            })
        },
        checkList(path, name, id, fileSize, hash, index) {
            $(".curtain").css("display", "block");
            let that = this
            that.disabledInp = true
            that.progressBar = true
            let iscp_port
            if (sessionStorage.getItem("iscp_port")) {
                iscp_port = sessionStorage.getItem("iscp_port");
            } else {
                iscp_port = ""
            }
            let Authentication = sessionStorage.getItem("Authentication");
            const timestamp = new Date().getTime() + ""
            let userId = sessionStorage.getItem("userId");
            let sign = sm3(timestamp + "&" + userId)
            that.fileName = name
            wx.invoke("ext_Net_FragmentUpload", {
                data: {
                    serverAddress: localUrlLink + iscp_port + `/tjAiAssistant/storage/splitUpload2?channelId=${id}`,
                    filePath: path,
                    fragmentSize: that.CHUNK_SIZE,
                    fileName: name,
                    fileHash: hash ? hash : '',
                    upLoadFragmentIndex: index ? index : '',
                    channelId: id,
                    headerData: {
                        sign: sign,
                        userId: userId,
                        type: '',
                        timestamp: timestamp,
                        Authentication: Authentication,
                    }
                },
            }, function (res) {
                console.log("文件上传结果", res)
                if (res.err_msg.endsWith(":ok")) { //成功结果
                    //上传完成
                    // that.recording(id)
                    addPendingData(106, id)
                    that.uploadComplete(id, name, fileSize)
                } else if (res.err_msg.endsWith(":cancel")) {
                    that.cleanData();
                    return
                } else {
                    //上传失败
                    if (that.myindex != Number(res.upLoadFragmentIndex)) {
                        that.myindex = Number(res.upLoadFragmentIndex);
                        that.retryNum = 0;
                    }
                    setTimeout(() => {
                        if (that.retryNum > 4) {
                            $(".curtain").css("display", "none");
                            // that.retryNum = 0
                            var btnArray = ["取消", "确定"];
                            var i = 0
                            mui.confirm(
                                "是否进行重试？",
                                "上传失败",
                                btnArray,
                                (e) => {
                                    if (i > 0) return
                                    i++
                                    if (e.index == 1) {
                                        that.checkList(path, name, id, fileSize, res.fileHash, res.upLoadFragmentIndex)
                                    } else {
                                        that.cleanData()
                                    }
                                }
                            );
                        } else {
                            that.retryNum++

                            that.checkList(path, name, id, fileSize, res.fileHash, res.upLoadFragmentIndex)
                        }

                    }, (that.retryNum + 1) * 1000)

                }
            })
        },
        calcFileSize(fileSize) {
            let kbf = (Math.floor((fileSize / 1024) * 100) / 100).toFixed(2);
            if (kbf > 1000) {
                //显示 MB
                return (Math.floor((fileSize / (1024 * 1024)) * 100) / 100).toFixed(2) + 'MB';
            }
            return kbf + 'KB';
        },
        cleanData() {
            this.disabledInp = false
            this.progressBar = false
        },
        async uploadComplete(id, name, fileSize) {
            try {
                console.log("上传完成", id);
                const userId = sessionStorage.getItem("userId");
                let param = {
                    "userId": userId,
                    "channelId": id,
                    "type": this.writingType,
                    "modelType": "BAIDU", //getLargeModelType(),
                    "timestamp": new Date().getTime() + "",
                };
                let AuthenticationSession = sessionStorage.getItem("Authentication");
                let data = JSON.stringify(param);
                let sign = sm3(data);
        
                // 构建请求配置
                const requestOptions = {
                    method: "POST",
                    headers: {
                        "Content-Type": "application/json;charset=UTF-8",
                        Authentication: AuthenticationSession,
                        sign: sign
                    },
                    body: data
                };
        
                // 发起请求
                const response = await fetch(localUrlLink + iscp_port + "/tjAiAssistant/writing/word2Md", requestOptions);
        
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
        
                const res = await response.json();
                $(".curtain").css("display", "none");
        
                const responseSign = response.headers.get("sign");
                if (sm3(res.resultValueStr) === responseSign) {
                    let Authentication = response.headers.get("Authentication");
                    if (res.code === 200) {
                        if (Authentication) {
                            sessionStorage.setItem("Authentication", Authentication);
                        }
                        let attach = res.resultValue;
                        if (0 === this.fileType) {
                            let suffix = name.split('.').reverse()[0];
                            let img = "img";
                            if (this.pdfSuffix.includes(suffix.toLocaleLowerCase())) {
                                img = "pdf";
                            } else if (this.imgSuffix.includes(suffix.toLocaleLowerCase())) {
                                img = "img";
                            }
                            this.form.notificationFile = {
                                id: attach.channelId,
                                fileName: name,
                                type: img.toUpperCase(),
                                img: img,
                                size: fileSize,
                                fileSize: calcFileSize(fileSize),
                                viewId: id
                            };
                        } else if (1 === this.fileType) {
                            this.improveFile = {
                                id: attach.channelId,
                                fileName: name,
                                type: 'WORD',
                                img: "word",
                                size: fileSize,
                                fileSize: calcFileSize(fileSize),
                                viewId: id
                            };
                        } else if (2 === this.fileType) {
                            this.form.recordFile = {
                                id: attach.channelId,
                                fileName: name,
                                type: 'WORD',
                                img: "word",
                                size: fileSize,
                                fileSize: calcFileSize(fileSize),
                                viewId: id
                            };
                        }
                    } else {
                        let msg = res.resultValue;
                        if ('文件不能为空'!== msg) {
                            msg = "请稍后再试";
                        }
                        mui.toast(msg, {
                            duration: 1000,
                            type: 'div'
                        });
                    }
                }
                this.fileType = -1;
            } catch (e) {
                $(".curtain").css("display", "none");
                this.fileType = -1;
                mui.toast('请稍后再试', {
                    duration: 1000,
                    type: 'div'
                });
            }
        },
        //开始录音
        startTalk(type) {
            if(0 != this.voiceType) {
                mui.toast('正在录音.', {
                    duration: 'long',
                    type: 'div'
                })
            }else {
                this.voiceType = type
                this.voiceTxt = {
                    ind: '',
                    old: ''
                }
                if(1 == this.voiceType) {
                    this.voiceTxt.ind = this.form.subjectTitle
                }else if(2 == this.voiceType) {
                    this.voiceTxt.ind = this.form.highlight
                }else if(3 == this.voiceType) {
                    this.voiceTxt.ind = this.requireText
                }
                this.getMeToken()
                // if(1 == this.voiceType) {
                //     startLuyin(this, 'voiceSubjectTitle', 'subjectTitle', this.form)
                // }else if(2 == this.voiceType) {
                //     startLuyin(this, 'voiceHighlight', 'highlight', this.form)
                // }else if(3 == this.voiceType) {
                //     startLuyin(this, 'voiceRequireText', 'requireText')
                // }
            }
        },
        //停止录音
        stopTalk(type) {
            this.stopTalkCallBack()
            this.stopRecorder()
            // if(1 == type) {
            //     endLuyin(this, 'voiceSubjectTitle', 'subjectTitle', this.form, this.stopTalkCallBack())
            // }else if(2 == type) {
            //     endLuyin(this, 'voiceHighlight', 'highlight', this.form, this.stopTalkCallBack())
            // }else if(3 == type) {
            //     endLuyin(this, 'voiceRequireText', 'requireText', this, this.stopTalkCallBack())
            // }
        },
        stopTalkCallBack() {
            var voiceInput = null;
            var voiceTextarea = null;
            var _text = '';
            if(1 == this.voiceType) {
                _text = this.form.subjectTitle
                voiceInput = document.getElementById('voiceSubjectTitle')
            }else if(2 == this.voiceType) {
                _text = this.form.highlight
                voiceTextarea = document.getElementById('voiceHighlight')
            }else if(3 == this.voiceType) {
                _text = this.requireText
                voiceInput = document.getElementById('voiceRequireText')
            }

            if(voiceInput) {
                voiceInput.setSelectionRange(_text.length, _text.length)
                // voiceInput.focus()
                voiceInput.scrollLeft = voiceInput.scrollWidth
            }
            if(voiceTextarea) {
                voiceTextarea.setSelectionRange(_text.length, _text.length)
                // voiceTextarea.focus()
                voiceTextarea.scrollTop = voiceTextarea.scrollHeight
            }
            this.voiceType = 0
        },

        getMeToken() {
            let _that = this
            var iscp_port = ''
            if (sessionStorage.getItem("iscp_port")) {
                iscp_port = sessionStorage.getItem("iscp_port");
            }
            userId = sessionStorage.getItem("userId");
            let AuthenticationSession = sessionStorage.getItem("Authentication");
            let timestamp = new Date().getTime() + ""
            let data = {
                "userId": userId,
                "timestamp": timestamp,
            }
            const datas = JSON.stringify(data)
            let sign = sm3(datas);
            $.ajax({
                url: localUrlLink + iscp_port + "/tjAiAssistant/soundRecording/thirdparty",
                type: "post",
                async: false, //是否同步，false表示同步请求
                dataType: "json",
                data: datas,
                headers: {
                    "Content-Type": "application/json;charset=UTF-8",
                    sign: sign,
                    Authentication: AuthenticationSession,
                },
                success: (res, txt, xhr) => {
                    if (sm3(res.resultValueStr) == xhr.getResponseHeader("sign")) {
                        let Authentication = xhr.getResponseHeader("Authentication")
                        if (res.code == 200) {
                            if (Authentication) {
                                sessionStorage.setItem("Authentication", Authentication);
                                _that.WS_URL =
                                    `ws://127.0.0.1:${iscp_port}/websocket/asr/i?token=${res.resultValue}&capacityCode=${_that.CAPACITY_CODE}&language=${_that.LANG}&code=${_that.MODEL_CODE}&sessionId=${_that.VoiceItemID}`
                                if (!('WebSocket' in window)) {
                                    return
                                }
                                if (_that.count < 1) {
                                    wx.invoke("multiWindows_subscribe", { channelId: _that.VoiceItemID }, function (res) {
                                        console.log(res, "订阅返回结果")
                                        console.log(res.data.message, "信息")
                                        if (res.data.method == "onMessage String" && res.data.channelId == _that.VoiceItemID) {
                                            _that.onMessage(res)
                                        } else if (res.data.method == 'onReconnectFinishAndDisconn') {
                                            //重连失败处理
                                            _that.stopVB()
                                        }
                                    });
                                }
                                _that.count++
                                wx.invoke("ext_AudioRecorder_Start", {
                                    data: {
                                        channelId: _that.VoiceItemID,
                                        socketUrl: _that.WS_URL
                                    }
                                },
                                    function (res) {
                                        if (res.err_msg === 'ext_AudioRecorder_Start:ok') {
                                            //成功处理
                                            _that.checkClick = 1
                                            _that.checkSwitch = true
                                        }

                                        if (res.err_msg === 'ext_AudioRecorder_Start:fail') {
                                            //失败处理
                                        }
                                        if (res.err_msg === 'ext_AudioRecorder_Start:cancel') {
                                            //取消处理
                                        }
                                        if (res.err_msg === 'ext_AudioRecorder_Start:not_support ') {
                                        }
                                    })
                            }
                        } else {
                            mui.toast(res.resultValue, {
                                duration: 'long',
                                type: 'div'
                            })
                        }
                    }
                },
                error: (e) => {
                    mui.toast('请求异常,请稍后再试', {
                        duration: 1000,
                        type: 'div'
                    })
                },
            })
        },
        onOpen(evt, way, afterOpen) {
            let _that = this
            this.checkSwitch = true
            wx.startRecordVoiceBuffer({
                maxDuration: 100000000,
                sampleRate: 16000
            });
            wx.onRecordBufferReceived(function (res) {
                if (_that.isflageIOX) {
                    var a = ''
                    if (_that.bufferData.length == 26) {
                        _that.bufferData.forEach((item) => {
                            a += item
                            _that.bufferData = []
                        })
                        // _that.stopRecorder()
                        _that.doSend(a);
                    } else {
                        _that.bufferData.push(res.buffer)
                    }
                } else {

                    _that.doSend(res.buffer);
                }
            })
            if (!$(this).hasClass("stop")) {
                $(this).addClass("stop");
                let i = 0;
                $(this).data("interval", window.setInterval(function () {
                    $(".record-time").html((++i) + "s");
                }, 1000, i));
            }
        },
        doSend(message) {
            this.myWebsocket.readyState === 1 && this.myWebsocket.send(message);
        },
        onMessage(evt) {
            try {
                // const data = JSON.parse(evt.data);
                const data = JSON.parse(evt.data.message);
                console.log(evt.data,"内容")
                if (data.code == 200) {
                    // 这一行是赋值的
                    data.word = data.word.replace(/[|]/g, '\n')
                    data.word = data.word.replace(/[\n]/g, '\n\n')
                    this.insertContent(data)
                    // if (data.completed == true) {
                    //     this.voiceTxt.ind += data.word.length
                    //     this.voiceTxt.old = ''
                    //     this.inputDom.setSelectionRange(this.voiceTxt.ind, this.voiceTxt.ind)
                    //     setTimeout(() => {
                    //         this.inputDom.setSelectionRange(this.voiceTxt.ind, this.voiceTxt
                    //             .ind)
                    //     });
                    // }
                } else if (data.code == 'E000004') {
                    mui.toast("当前已达到最大并发量限制,请稍后再试", {
                        duration: 'long',
                        type: 'div'
                    })
                    this.stopRecorder()
                } else {
                    mui.toast(data.code + "语音服务异常", {
                        duration: 'long',
                        type: 'div'
                    })
                    this.stopRecorder()
                }
            } catch (error) {
                throw new Error('解析错误!' + error);
            }
        },
        insertContent(data) {
            let txt = data.word
            let ctxt = ''
            if(data.completed) {
                //完成
                this.voiceTxt.old += txt
                ctxt = this.voiceTxt.old
            }else{
                //未完成
                ctxt = this.voiceTxt.old + txt
            }
            var voiceInput = null;
            var _text = this.voiceTxt.ind + ctxt;
            if(1 == this.voiceType) {
                this.form.subjectTitle = this.voiceTxt.ind + ctxt
                voiceInput = document.getElementById('voiceSubjectTitle')
            }else if(2 == this.voiceType) {
                this.form.highlight = this.voiceTxt.ind + ctxt
                voiceInput = document.getElementById('voiceHighlight')
            }else if(3 == this.voiceType) {
                this.requireText = this.voiceTxt.ind + ctxt
                voiceInput = document.getElementById('voiceRequireText')
            }

            if(voiceInput) {
                voiceInput.setSelectionRange(_text.length-1, _text.length)
                voiceInput.focus()
                voiceInput.scrollLeft = voiceInput.scrollWidth
            }
        },
        insertTxt(content, index, txt, del) {
        },
        stopRecorder(num) {
            let _this = this
            wx.invoke("ext_AudioRecorder_Stop", {
                data: {}
            },
                function (res) {
                    if (res.err_msg === 'ext_AudioRecorder_Stop:ok') {
                        _this.stopVB(num)
                    }
                    if (res.err_msg === 'ext_AudioRecorder_Stop:fail') {
                        //失败处理
                        console.log(res);
                    }
                    if (res.err_msg === 'ext_AudioRecorder_Stop:cancel') {
                        //取消处理
                        console.log(res);
                    }
                    if (res.err_msg === 'ext_AudioRecorder_Stop:not_support ') {
                        _this.stopVB(num)
                        wx.stopRecordVoiceBuffer({});
                        // if (_this.myWebsocket) {
                        _this.myWebsocket.close();
                    }
                })
        },
        stopVB(num) {
            //成功处理
            this.time = clearInterval(this.time)
            // this.flag = true
            this.checkSwitch = false
            this.checkClick = 0
            $(this).removeClass("stop");
            window.clearInterval($(this).data("interval"));
            $(".record-time").html("");
        },
        handleScrollBottom(refName) {
            // this.$nextTick(() => {
                let scrollElem = this.$refs[refName];
                if(scrollElem) {
                    $(scrollElem).stop(true, true)
                    $(scrollElem).animate({ scrollTop: $(scrollElem).prop('scrollHeight')},20)
                }
            // })
        },
        preview(item) {
            myPreviewFile(item)
        },
        //分享
        shareIgw(item) {
            if(!item.id) {
                return
            }
            shareIgw({
                sceneNo: '106',
                shareType: 1,
                attchId: item.id
            })
         },
        //文件发送邮箱
        sendMyEmail(result) { 
            if(!result.id) {
                return
            }
            mySendMail('会议助手', "answerAttach="+result.id, 10, 6)
        },
        //同步到内网统一入口
        syncToInner(result) {
            if(!result.id) {
                return
            }
            mySyncToInner('会议助手', "answerAttach="+result.id, 10, 6)
        },
        //复制按钮
        copy() {
            let text1 = this.clipboard.content;
            var clipboard = new Clipboard(".tag-read", {
                // 通过target指定要复印的节点
                text: function () {
                    return text1;
                },
            });
            clipboard.on("success", (e) => {
                addOperator(2, 11, "复制文本", 1, 1, "复制成功");
                mui.toast("复制成功", {
                    duration: "long",
                    type: "div"
                });
            });
            clipboard.on("error", (e) => {
                addOperator(2, 11, "复制文本", 1, 0, "复制失败");
            });
        },
        // 判断安卓还是ios
        compatibleInput() {
            //获取浏览器的userAgent,并转化为小写
            var ua = navigator.userAgent.toLowerCase();
            //判断是否是苹果手机，是则是true
            var isIos = ua.indexOf("iphone") != -1 || ua.indexOf("ipad") != -1;
            if (isIos) {
                this.isflageIOX = true;
            } else {
                this.isflageIOX = false;
            }
        },
        home() {
            // $(location).attr("href", "index.html");
            $(location).attr("href", "../../voiceRecordingList.html");
        },
        createSgin(data) {
            let hashData = sm3(data);
            let hashData_last = sm3(hashData);
            hashData_last = hashData_last.substr(0, 5);
            hashData += hashData_last;
            let sign = hashData;
            return sign;
        },
        sendEmail() {
            console.log('发送邮箱')
        },
        handleNoSend(){
            if(!this.curPId) {
                mui.toast("请选择修改内容", { duration: "long", type: "div" });
            }else{
                mui.toast("请输入要求", { duration: "long", type: "div" });
            }
        }
    }
})